import { Injectable } from '@nestjs/common';
import {RedisService} from 'nestjs-redis'
import {Redis} from 'ioredis'
@Injectable()
export class RedisUtilsService {
  public client:Redis
  constructor(private redisService:RedisService){
    // this.getClient()
  }

  onModuleInit(){
    this.getClient()
  }

  public getClient():void{
    this.client = this.redisService.getClient()
  }

  //设置值
  public async set(key:string,value:{[key:string]:any}|string,second?:number):Promise<void>{
     value = JSON.stringify(value)
     if(!second){
       await this.client.setex(key,60*60*24,value) //过期时间一天
     }else {
       await this.client.set(key,value,'EX',second)
     }
  }

  //获取值
  public async get(key:string):Promise<{[key:string]:any}|string>{
   const result = await this.client.get(key)
   console.log(result);
   if(result){
     return JSON.parse(result)
   }else{
    return null
   }
  }

  //删除值
  public async del(key:string):Promise<void>{
   await this.client.del(key)
  }

  //关闭连接
  public async flushall():Promise<void>{
   await this.client.flushall()
  }
}
